<?php

namespace app\common\model;

use think\Model;
use think\Db;

class CandyMachine extends Model
{
    // 玩家信息
    public function owner()
    {
        return $this->belongsTo('Nsuser', 'uid', 'id')->field('id,username,mobile');
    }
    // 糖果机类型
    public function candymType()
    {
        return $this->belongsTo('CandymType', 'type', 'type_id')
            ->field('type_id,type_name,candy_pic');
    }

    /**
     * 获取列表
     *
     * @param [type] $map
     * @return void
     */
    public function getList($map, $size = null, $field = '*')
    {
        $list = $this->with('owner,candymType')
            ->where($map)->field($field)->order('status,create_time Desc')->paginate($size);
        return $list;
    }

    /**
     *  玩家购买糖果机
     * 
     * @param [type] $data [description]
     */
    public function addInfo($data)
    {
        $count = $this->where([
                'uid' => $data['uid'],
                'status' => 0    
            ])->count();
        if ($count >= 3) {
            return msg_code('糖果机已购满3台');
        }

        $coin = config('coin');
        $acc_type = $coin[$data['coin_id']];

        $acc = db('user')->where('uid', $data['uid'])->value($acc_type);
        $cm = db('candym_type')->where('type_id', $data['type_id'])->find();
        if ($cm) {
            if ($acc < $cm['price']) {
                return msg_code('账户余额不足');
            }

            $endtime = strtotime("{$cm['lifetime']} days");
            $addData = [
                'uid' => $data['uid'],
                'type' => $cm['type_id'],
                'cost' => '消费'.$cm['price'].config('coinText')[$acc_type],
                'candy_total' => $cm['candy_num'],
                'start' => date('Y-m-d'),
                'end' => date('Y-m-d', $endtime),
                'left_days' => $cm['lifetime'],
                'lifetime' => $cm['lifetime'],
                'status' => 0
            ];

            Db::startTrans();
            try {
                model('User')->updateUserAcc($data['uid'], -$cm['price'], $acc_type, '购买'.$cm['type_name']);
                // 查找推荐人，派发奖励
                $this->giveAward($data['uid'], $cm['price']);
                $rst = $this->save($addData);
                Db::commit();
                return msg_code('已买入', $rst);
            } catch (Exception $e) {
                Db::rollback();
                return msg_code($e->getMessage());
            }
        }
        return msg_code('不存在此类型糖果机');
    }

    /**
     * 派发奖励
     * 
     * @param  [type] $uid [description]
     * @param  [type] $num [description]
     * @return [type]      [description]
     */
    private function giveAward($uid, $num)
    {
        $info = Db::name('user')->where('uid', $uid)->field('pid,name')->find();
        // 存在直推
        if ($info['pid']) {
            $num = $num * config('zt_rate') / 100;
            model('User')->updateUserAcc($info['pid'], $num, 'tg_coin', '玩家'.$info['name'].'购买糖果机，直推奖励');
        }

    }


}
